using System.Collections;
using GameKit.Core.Context;
using GameKitUnity.Core;
using OneGame.Gameplay.UI;
using UnityEngine;

namespace OneGame.Gameplay.Monster
{
    public class MonsterStateView : MonoBehaviour, IStateView
    {
        [SerializeField]
        Transform stateTransform;

        private UIStateView _stateView;
        private Coroutine _hideCoroutine;

        public void SetHealth(int current, int max, int diff)
        {
            ShowState();
            _stateView.ShowHealth(current, max, diff);
        }

        public void ShowState()
        {
            if (!_stateView)
            {
                if (GlobalContext.TryGet("UICanvas", out Transform canvasTransform))
                {
                    var go = PoolManager.Instance.Get("UIStateView");
                    _stateView = go.GetComponent<UIStateView>();
                    _stateView.StateTransform = stateTransform;
                    var rectTransform = go.GetComponent<RectTransform>();
                    rectTransform.SetParent(canvasTransform, false);
                    _stateView.Show(true);
                }
            }

            if (_hideCoroutine != null)
            {
                StopCoroutine(_hideCoroutine);
            }

            _hideCoroutine = this.StartCoroutine(HideStateAfterDelay(3f));
        }

        private IEnumerator HideStateAfterDelay(float f)
        {
            yield return new WaitForSeconds(f);
            HideState();
        }

        public void HideState()
        {
            if (_hideCoroutine != null)
            {
                StopCoroutine(_hideCoroutine);
            }

            _stateView?.Show(false);
            _stateView = null;
        }
    }
}